package cn.edu.scau.cmi.linhongxin.composite.safe;

import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.Alert.AlertType;

public class SafeController implements Initializable{
	@FXML
	private TextField createInput;
	@FXML
	private ChoiceBox<String> teamChoiceBox;
	@FXML
	private Button personButton;
	@FXML
	private Button teamButton;
	@FXML
	private Button delete;
	@FXML
	private TreeView<String> orgTreeView;
	private String name;
	private String team;
	private Team org;
	private TreeItem<String> rootNode;
	private String init="组织";
	private List<String> teamList;
	private List<String> nameList;
	private ObservableList<String> obList;
	private ChangeListener<Number> choiceBoxListener;
	private List<String> deleteTargetList;
	private boolean isRoot;
	
	@Override
	public void initialize(URL location,ResourceBundle resources) {
		team=null;
		teamList=new ArrayList<String>();
		teamList.add(init);
		nameList=new ArrayList<String>();
		nameList.add(init);
		choiceBoxListener=new ChangeListener<Number>() {
			@Override
			public void changed(ObservableValue<? extends Number>observable,Number oldValue,Number newValue) {
				team=teamList.get(newValue.intValue());
			}
		};
		obList=FXCollections.observableArrayList(teamList);
		teamChoiceBox.getSelectionModel().selectedIndexProperty().addListener(choiceBoxListener);
		teamChoiceBox.setItems(obList);
		refresh();
		
		rootNode=new TreeItem<String>(init);
		rootNode.setExpanded(true);
		orgTreeView.setRoot(rootNode);
		
		deleteTargetList=new ArrayList<String>();
		isRoot=false;
		orgTreeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<String>>() {
			@Override
			public void changed(ObservableValue<? extends TreeItem<String>> observable, TreeItem<String> oldValue,
					TreeItem<String> newValue) {
				deleteTargetList.clear();
				isRoot = false;
				getAllChildrenName(newValue);
				if(newValue.equals(rootNode)) isRoot = true;
			}
		});
	}
	//refresh choiceBox and creatInput
	private void refresh() {
		createInput.clear();
		teamChoiceBox.getSelectionModel().selectFirst();
	}
	//put into deleteTargetList
	private void getAllChildrenName(TreeItem<String> root) {
		// TODO Auto-generated method stub
		deleteTargetList.add(root.getValue());
		for(TreeItem<String> item : root.getChildren()) {
			getAllChildrenName(item);
		}
	}
	public void addPerson(ActionEvent e) {
		getInputInfo();
		if(!verifyInput()) {
			refresh();
			return;
		}
		TreeItem<String> treeNode = new TreeItem<String>(name);
		// 往TreeView中添加
		putInTreeView(rootNode, treeNode, team);
		// 往组织中添加
		Organization node = new Person(name);
		putInList(org, node, team);
		nameList.add(node.getName());
		refresh();
	}
	
	public void addTeam(ActionEvent e) {
		getInputInfo();
		if(!verifyInput()) {
			refresh();
			return;
		}
		Organization node = new Team(name);
		TreeItem<String> treeNode = new TreeItem<String>(name);
		treeNode.setExpanded(true);
		// add into TreeView
		putInTreeView(rootNode, treeNode, team);
		// 往组织中添加
		putInList(org, node, team);		
		// 将新的团队添加到 TeamList表中 以便在选择框中显示 并且刷新选择框
		obList.add(node.getName());
		teamList.add(node.getName());
		// add new team,refresh
		nameList.add(node.getName());
		refresh();
	}
	// 获取输入框和选择框的信息 name 和 team
		private void getInputInfo() {
			name = createInput.getText();
			team = teamChoiceBox.getSelectionModel().getSelectedItem();
		}
			
		// 往组织中添加结点 pre为node的上一个结点
		private boolean putInList(Organization preNode, Organization node, String pre) {
			if(preNode instanceof Team) {
				Team team = (Team)preNode;
				if(team.getName().compareTo(pre) == 0) {
					team.add(node);
					return true;
				}
				Iterator<Organization> itor = team.elements();
				while(itor.hasNext()) {
					Organization child = itor.next();
					boolean res = putInList(child, node, pre);
					if(res) return true;
				}
			}
			return false;
		}
		
		// 往TreeView中添加相应的结点 pre为node的上一个结点
		private boolean putInTreeView(TreeItem<String> preNode, TreeItem<String> node, String pre) {
			if(preNode.getValue().compareTo(pre) == 0) {
				preNode.getChildren().add(node);
				return true;
			}
			ObservableList<TreeItem<String>> childList = preNode.getChildren();
			for(TreeItem<String> item : childList) {
				boolean res = putInTreeView(item, node, pre);
				if(res) return false;
			}
			return false;
		}
		// 删除组织中的结点 和 TreeView中的结点
		public void deleteNode(ActionEvent e) {
			// 通过监听器获取要删除的结点 得到相应的名字串
			if(deleteTargetList.size() == 0) return;
			// 不允许删除 rootNode 弹窗警告
			if(isRoot) {
				Alert alert = new Alert(AlertType.WARNING);
				alert.setHeaderText(null);
				alert.setContentText("不允许删除");
				alert.show();
				return;
			}
			String str;
			for(int i = 0; i < deleteTargetList.size(); i++) {
				str = deleteTargetList.get(i);
				deleteInList(nameList, str);
				deleteInList(obList, str);
				deleteInList(teamList, str);
			}
			deleteInTreeView(rootNode, deleteTargetList.get(0)); // 只要删除第一个 所有children都会被删除
		}
		// 在TreeView中删除某一个Organization
		private boolean deleteInTreeView(TreeItem<String> root, String str) {
			ObservableList<TreeItem<String>> children = root.getChildren();
			if(children.size() > 0) {
				for(int i = 0; i < children.size(); i++) {
					if(children.get(i).getValue().compareTo(str) == 0) {
						children.remove(i);
						return true;
					}
					boolean res = deleteInTreeView(children.get(i), str);
					if(res) return true;
				}
			}
			return false;
		}
		
		// 在List中删除某一个Organization
		private void deleteInList(List<String> list, String str) {
			for(int i = 0; i < list.size(); i++) {
				if(list.get(i).compareTo(str) == 0) {
//					System.out.println("remove = " + list.get(i));
					list.remove(i);
					break;
				}
			}		
		}
		// 判断输入合法 并且不允许有重复的名字
		private boolean verifyInput() {
			String str = name;
			if(str == null || str.length() == 0) {
				// 输入不合法 弹出窗口提示
				Alert alert = new Alert(AlertType.WARNING);
				alert.setHeaderText(null);
				alert.setContentText("输入不合法");
				alert.show();
				return false;			
			} else {
				// 根据nameList 判断是否有名字重复
				for(String s : nameList) {
					if(s.compareTo(str) == 0) {
						Alert alert = new Alert(AlertType.WARNING);
						alert.setHeaderText(null);
						alert.setContentText("不允许重复的名字");
						alert.show();
						return false;
					}
				}			
			}
			return true;
		}
}
